<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>tween.js动画库的使用</title>
    <style>
      body {
        margin: 0;
        overflow: hidden;
        /* 隐藏body窗口区域滚动条 */
      }
    </style>
    <!--引入three.js三维引擎-->
    <!-- <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script> -->
    <!-- <script src="http://www.yanhuangxueyuan.com/threejs/build/three.js"></script> -->
    <!-- Three.js-master 包示例中的用法 examples/js/controls/OrbitControls.js  版本要匹配-->
    <script type="importmap">
      {
        "imports": {
          "three": "../../node_modules/three/build/three.module.js",
          "three/addons/": "../../node_modules/three/examples/jsm/",
          "@tweenjs/tween.js": "../../node_modules/@tweenjs/tween.js/dist/tween.esm.js"
        }
      }
    </script>
  </head>
  <body>
    <script type="module">
      import {
        RAFTime,
        sphereMesh,
        cylinderMesh,
        v2ToV3,
      } from "../../util/index.js";

      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      import Stats from "three/addons/libs/stats.module.js";
      import { GUI } from "three/addons/libs/lil-gui.module.min.js";
      import TWEEN from "@tweenjs/tween.js";

      var camera;
      var controls;
      /**
       * 创建场景对象Scene
       */
      var scene = new THREE.Scene();
      // 创建集合
      var group = new THREE.Group();

      // --------------------------------------------------------------------------------------------------tween.js的事件 onStart/onUpdate/onComplete
      const R = 100; //相机圆周运动的半径
      new TWEEN.Tween({ angle: 0 })
        .to({ angle: Math.PI * 2 }, 6000)
        .onStart(() => {
          console.log("动画开始！");
        })
        .onUpdate(function (obj) {
          camera.position.x = R * Math.cos(obj.angle);
          camera.position.z = R * Math.sin(obj.angle);
          camera.lookAt(0, 0, 0);
        })
        .onComplete(() => {
          // controls.target.set(0, 0, 0);
          controls.target = new THREE.Vector3(0, 0, 0);
          controls.update(); // 执行controls.update(); 相机控件内部会执行camera.lookAt(controls.target)
          console.log("动画正常结束！");
        })
        .start();

      const lineGeometry = new THREE.BufferGeometry(); //创建一个几何体对象
      // 三维样条曲线
      const curve = new THREE.CatmullRomCurve3([
        new THREE.Vector3(-50, 20, 90),
        new THREE.Vector3(-10, 40, 40),
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(60, -60, 0),
        new THREE.Vector3(70, 0, 80),
      ]);
      const pointsArr = curve.getSpacedPoints(100); //曲线取点
      lineGeometry.setFromPoints(pointsArr); //pointsArr赋值给顶点位置属性

      const pos = lineGeometry.attributes.position;
      const count = pos.count; //顶点数量
      // 计算每个顶点的颜色值
      const colorsArr = [];
      // 手动实现颜色渐变
      // for (let i = 0; i < count; i++) {
      //   const percent = i / count; //点索引值相对所有点数量的百分比
      //   //根据顶点位置顺序大小设置颜色渐变
      //   // 红色分量从0到1变化，蓝色分量从1到0变化
      //   colorsArr.push(percent, 0, 1 - percent); //蓝色到红色渐变色
      // }

      // lerp/lerpColors方法实现颜色渐变
      const c1 = new THREE.Color(0x00ffff); //曲线起点颜色 青色
      const c2 = new THREE.Color(0xffff00); //曲线结束点颜色 黄色
      for (let i = 0; i < count; i++) {
        const percent = i / count; //点索引值相对所有点数量的百分比
        //根据顶点位置顺序大小设置颜色渐变
        // const c = new THREE.Color();
        // c.lerpColors(c1, c2, percent);
        const c = c1.clone().lerp(c2, percent); //颜色插值计算
        colorsArr.push(c.r, c.g, c.b);
      }

      //类型数组创建顶点颜色color数据
      const colors = new Float32Array(colorsArr);
      // 设置几何体attributes属性的颜色color属性
      lineGeometry.attributes.color = new THREE.BufferAttribute(colors, 3);

      const lineMaterial = new THREE.LineBasicMaterial({
        vertexColors: true, //使用顶点颜色渲染
      });
      const line = new THREE.Line(lineGeometry, lineMaterial);

      scene.add(line);

      /**
       * 辅助坐标系 参数250表示坐标系大小，可以根据场景大小去设置
       */
      var axesHelper = new THREE.AxesHelper(1000);
      scene.add(axesHelper);

      var loader = new THREE.CubeTextureLoader();
      // 所有贴图在同一目录下，可以使用该方法设置共用路径
      loader.setPath("../../public/images/cube/");

      // 平行光
      var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      // 平行光辅助对象
      const directionalLightHelper = new THREE.DirectionalLightHelper(
        directionalLight,
        10
      );
      scene.add(directionalLightHelper);
      // 设置光源位置
      directionalLight.position.set(60, 60, 60);
      scene.add(directionalLight);
      // 设置用于计算阴影的光源对象
      directionalLight.castShadow = true;

      //环境光
      var ambient = new THREE.AmbientLight(0x050505);
      scene.add(ambient);

      /**
       * 相机设置
       */
      var width = window.innerWidth; //窗口宽度
      var height = window.innerHeight; //窗口高度
      var k = width / height; //窗口宽高比
      // var s = 1; //三维场景显示范围控制系数，系数越大，显示的范围越大
      // //创建相机对象
      // var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 100);
      // ---------------------------------------目8.9 环境贴图，使用PerspectiveCamera比OrthographicCamera更真正，人眼视角
      camera = new THREE.PerspectiveCamera(60, k, 1, 2000);
      camera.position.set(200, 100, 200); //设置相机位置
      camera.lookAt(scene.position); //设置相机方向(指向的场景对象)

      /**
       * 创建渲染器对象
       */
      var renderer = new THREE.WebGLRenderer();
      renderer.setSize(width, height); //设置渲染区域尺寸
      renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
      // 设置渲染器，允许光源阴影渲染
      renderer.shadowMap.enabled = true;
      document.body.appendChild(renderer.domElement); //body元素中插入canvas对象

      // 创建，轨迹控件---实现旋转/平移/缩放
      controls = new OrbitControls(camera, renderer.domElement);
      // 监听鼠标、键盘事件
      // controls.addEventListener("change");

      // ------------------------------------------------------------------------------------------渲染性能工具stats.js
      const stats = new Stats();
      stats.setMode(1);
      document.body.appendChild(stats.domElement);

      // ------------------------------------------------------------------------------------------交互界面工具gui.js
      const gui = new GUI();
      gui.close();
      //改变交互界面style属性
      gui.domElement.style.right = "0px";
      gui.domElement.style.width = "300px";

      // 界面分组
      const directionalLightFolder = gui.addFolder("平行光父文件夹");

      // directionalLightFolder.close();

      directionalLightFolder
        .addColor(directionalLight, "color")
        .name("平行光颜色")
        .step(0.1)
        .onChange(function (value) {
          directionalLight.color.set(value);
        });

      const directionalLightSubFolder =
        directionalLightFolder.addFolder("平行光子文件夹");

      directionalLightSubFolder
        .add(directionalLight, "intensity", 0, 10)
        .name("平行光强度")
        .step(0.1);

      // // 监听鼠标、键盘事件，实现 旋转/缩放/平移
      // function render() {
      //   renderer.render(scene, camera); //执行渲染操作
      // }

      // 递归函数,每1/60秒左右,调用一次自己
      const render = RAFTime((t) => {
        TWEEN.update();
        stats.update();
        renderer.render(scene, camera); //执行渲染操作
      });

      // 启动渲染---requestAnimationFrame周期性的渲染
      render();

      // 窗口大小变化后，设置画布 => 设置相机参数 => 更新投影矩阵
      window.onresize = function () {
        // 重置渲染器输出画布canvas尺寸
        renderer.setSize(window.innerWidth, window.innerHeight);
        // 全屏情况下：设置观察范围长宽比aspect为窗口宽高比
        camera.aspect = window.innerWidth / window.innerHeight;
        // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
        // 但是不会每渲染一帧，就通过相机的属性计算投影矩阵(节约计算资源)
        // 如果相机的一些属性发生了变化，需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
        camera.updateProjectionMatrix();
      };
    </script>
  </body>
</html>
